package com.soaptesting;

import java.util.Iterator;
import javax.xml.bind.JAXB;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SAAJResult;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.dom.DOMSource;

import com.soaptesting.jaxws.GetMsgs;
import com.soaptesting.jaxws.SaveMsg;

public class MsgManagerSOAPHandler {
	private static final String NAMESPACE_URI = "http://soaptesting.com/";
	private static final QName SAVE_MSG_NAME = new QName(NAMESPACE_URI, "saveMsg");
	private static final QName GET_MSG_NAME = new QName(NAMESPACE_URI, "getMsgs");
	
	private MessageFactory messageFactory;
	private MsgManagerAdapter msgMgrAdapter;
	
	public MsgManagerSOAPHandler() throws SOAPException
	{
		messageFactory = MessageFactory.newInstance();
		msgMgrAdapter = new MsgManagerAdapter();
	}
	
	public SOAPMessage handleSOAPRequest(SOAPMessage soapRequest) throws SOAPException
	{
		SOAPBody soapBody = soapRequest.getSOAPBody();
		Object responsePojo = null;
		
		for(Iterator iter = soapBody.getChildElements(); iter.hasNext();)
		{
			Object child = iter.next();
			if(child instanceof SOAPElement)
			{
				SOAPElement element = (SOAPElement)child;
				QName qname = element.getElementQName();
				if(SAVE_MSG_NAME.equals(qname))
				{
					responsePojo = handleSaveMsgRequest(element);
					break;
				}
				else if(GET_MSG_NAME.equals(qname))
				{
					responsePojo = handleGetMsgRequest(element);
					break;
				}
			}
		}
		
		SOAPMessage soapResponse = messageFactory.createMessage();
		soapBody = soapResponse.getSOAPBody();
		if(responsePojo != null)
		{
			JAXB.marshal(responsePojo, new SAAJResult(soapBody));
		}
		else
		{
			SOAPFault fault = soapBody.addFault();
			fault.setFaultString("Unrecognized SOAP request.");
		}
		return soapResponse;
	}

	private Object handleGetMsgRequest(SOAPElement element) {
		GetMsgs getMsgRequest = JAXB.unmarshal(new DOMSource(element), GetMsgs.class);
		return msgMgrAdapter.getMsgs(getMsgRequest);
	}

	private Object handleSaveMsgRequest(SOAPElement element) {
		SaveMsg saveMsgRequest = JAXB.unmarshal(new DOMSource(element), SaveMsg.class);
		return msgMgrAdapter.saveMsg(saveMsgRequest);
	}
	
	
	
}
